<?php
namespace Common\Controller;
use Think\Controller;

class SmsbaseController extends Controller {

	public $display = array(		//默认View配置
		'templateFile' => '',
		'charset' => '',
		'contentType' => '',
		'content' => '',
		'prefix' => '',
	);

	public $outVar = array();		//要输出的数据

	public function _initialize(){
		session_start();
		//测试模式
		if ($_REQUEST['newtest']) {
			!$_SERVER['HTTP_NEWAPPAUTH'] && $_SERVER['HTTP_NEWAPPAUTH'] = TRUE;
			!$_SERVER['HTTP_NEWSESSID'] && $_SERVER['HTTP_NEWSESSID'] = $_REQUEST['newtest'];
		}

		//APP身份验验证识别码
		$app_auth_codes = array(
			'pika_app' => 'fnunqn6ldamueHnYfoGk1pqTf6HIqnFw',		// \Think\Crypt::encrypt('pikaapp', md5('2016pika'));
		);



	}

	/**
	 * 类似TP View的assign方法
	 * @param	array	$name
	 * @param	string	$value
	 */
	public function assignOut($name, $value = '') {
		if(is_array($name)) {
			$this -> outVar = array_merge($this -> outVar, $name);
		} else {
			$this -> outVar[$name] = $value;
		}
	}

	/**
	 * 通用输出方法,可以自动判断是APP请求API还是Ajax还是网页请求,并自动选择渲染模板还是输出JSON
	 * @author	Baiyu	2017-01-05
	 * @param	array	$assign		要输出的数据
	 * @param	string	$type		手动指定输出类型 view为渲染模板 | json | jsonp | xml | eval
	 */
	public function output($assign, $type = 'view'){

		$type = strtolower($type);

		if (IS_AJAX || IS_APP && $type == 'view') {
			$type = 'json';
		}

		if ($type == 'view') {

			$this -> assign($this -> outVar);
			$this -> assign($assign);

			$this -> display(
				$this -> display['templateFile'],
				$this -> display['charset'],
				$this -> display['contentType'],
				$this -> display['content'],
				$this -> display['prefix']
			);

		} elseif (in_array($type, array('json', 'jsonp', 'xml', 'eval'))) {

			$output = array(
				'error' => 0,
				'error_msg' => '',
			);

			if (isset($assign['error']) && isset($assign['error_msg'])) {
				$output['error'] = $assign['error'];
				$output['error_msg'] = $assign['error_msg'];
				unset($assign['error']);
				unset($assign['error_msg']);
			}
			$output['data'] = array_merge($this -> outVar, $assign);

			//输出时要不转unicode, 不转义斜杠
//			$this -> ajaxReturn($output, strtoupper($type), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
			$this -> ajaxReturn($output, strtoupper($type));

		} else {
			//TODO 错误处理
		}
	}
}